package platform.upgrader;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.logging.Level;

import model.Preference;
import model.Settings;
import platform.PlatformObjectFactory;
import scripts.PermissionSetter;
import util.LoggingUtils;
import util.PlayerUtilities;

public class MacPlayerUpgrader extends PlayerUpgrader {
	private static final String UPDATE_SCRIPT_PATH_IN_JAR ="scripts/update_macplayer.sh";
	private static final String DEST_UPDATE_SCRIPT_PATH ="update_macplayer.sh";
	String versionName;
	
	@Override
	public void update(String versionName) {
		this.versionName=versionName;
		String scriptPath = Settings.SCRIPT_DIRECTORY +DEST_UPDATE_SCRIPT_PATH;
		createShellScript(scriptPath);
		giveExecutePermission(scriptPath);
		executeScriptIfExists(scriptPath);
		Preference.getInstance().setResendContentOnStartup(true);
		PlatformObjectFactory.getInstance().getCommandExecutor().resetPlayer();
	}
	
	private void executeScriptIfExists(String fileName) {
		File scriptFile = new File(fileName);
		if(scriptFile.exists()) {
			executeScriptFile(fileName);
		}
	}
	
	private void executeScriptFile(String fileName) {
		ProcessBuilder pb = new ProcessBuilder("./"+DEST_UPDATE_SCRIPT_PATH);
		pb.directory(new File(Settings.SCRIPT_DIRECTORY));
		Map<String, String> env = pb.environment();
		env.put("DMBPLAYER_PATH", new File("").getAbsolutePath());
		env.put("PLAYER_FILENAME", Settings.PLAYER_EXECUTABLE);
		if(this.versionName!=null && versionName.length()!=0) { 
			env.put("PLAYER_DOWNLOAD_LINK", "http://www.digitalmarketingbox.com/yang/newplayer/"+versionName+"/macplayer.tar.gz");
		} else {
			env.put("PLAYER_DOWNLOAD_LINK", "http://www.digitalmarketingbox.com/yang/newplayer/macplayer.tar.gz");
		}
		pb.redirectErrorStream(true);
		try {
			Process p = pb.start();
			printProcessOutput(p);
		} catch (IOException e) {
			e.printStackTrace();
			LoggingUtils.log(Level.SEVERE, "System Error in MacPlayerUpgrader .executeScriptFile(): "+e.getMessage(), e);
		}
		catch(Exception e)
		{
			LoggingUtils.log(Level.SEVERE, "System Error in MacPlayerUpgrader .executeScriptFile(): "+e.getMessage(), e);
		}
	}
	
	private void createShellScript(String fileName) {
		PlayerUtilities.copyFromJarToDirectory(UPDATE_SCRIPT_PATH_IN_JAR,fileName);
	}
	
	public void printProcessOutput(Process p) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
		InputStreamReader isr = new InputStreamReader(bis);
		BufferedReader br = new BufferedReader(isr);
		String line = null;
		while (null != (line = br.readLine())) {
			System.out.println(line);
		}
	}
	
	public void giveExecutePermission(String fileName) {
		PermissionSetter pg = new PermissionSetter();
		pg.givePermission(fileName, "a+x");
	}
}